package com.sctu.EMSApp;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.*;
import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.sctu.adapter.ViewPagerAdapter;
import com.sctu.bean.MyTravelNoteBean;
import com.sctu.bean.TravelNotesListPostBean;
import com.sctu.http.UrlConfig;
import com.sctu.httpvollry.GetVolleyHttp;
import com.sctu.util.SharePreferenceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by fll on 2015/12/24.
 */
public class MyTravelNoteActivity extends Activity implements ViewPager.OnPageChangeListener {

    private TextView textViewTitle, textViewTime, textViewAuthor, textViewContent;
    private List<MyTravelNoteBean.Results> resultsList = new ArrayList<MyTravelNoteBean.Results>();
    private ImageView backButton, sendCommentImg;
    private LinearLayout commentLinearLayout;
    private EditText editText;
    private ViewPager vp;
    private List<View> viewList = new ArrayList<View>();
    private List<ImageView> imageViewList = new ArrayList<ImageView>();
    private RelativeLayout relativeLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_travel_note_one);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        initView();
        initPager();
    }

    /**
     * 启动当前activity
     *
     * @param id
     * @param context
     */
    public static void actionStart(String id, Context context) {
        Intent intent = new Intent(context, MyTravelNoteActivity.class);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }


    public void initPager() {
        vp = (ViewPager) findViewById(R.id.my_travel_one_viewPager);
        vp.setOnPageChangeListener(MyTravelNoteActivity.this);
    }

    public void initView() {
        textViewTitle = (TextView) findViewById(R.id.my_travel_one_title);
        textViewTime = (TextView) findViewById(R.id.my_travel_one_time);
        textViewAuthor = (TextView) findViewById(R.id.my_travel_one_author);
        textViewContent = (TextView) findViewById(R.id.my_travel_one_content);
        backButton = (ImageView) findViewById(R.id.my_travel_one_back_button);
        commentLinearLayout = (LinearLayout) findViewById(R.id.my_travel_one_layout);
        sendCommentImg = (ImageView) findViewById(R.id.activity_travel_notes_send_comment_img);
        editText = (EditText) findViewById(R.id.activity_my_travel_notes_edit_txt);
        relativeLayout = (RelativeLayout) findViewById(R.id.my_travel_one_relative);

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        Intent intent = getIntent();
        final String id = intent.getStringExtra("id");
        sendCommentImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String comment = editText.getText().toString();
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("uid", String.valueOf(SharePreferenceUtil.getInstance(MyTravelNoteActivity.this).getKeyData("userId")));
                map.put("content", comment);
                map.put("content", comment);
                if (!comment.isEmpty() && !comment.equals("") && comment != null) {
                    GetVolleyHttp.getInstance(MyTravelNoteActivity.this).getStringPOSTJsonData(UrlConfig.URL_TRAVEL_NOTES_LIST_COMMENT + id, map,
                            listener1, errorlistener1);
                } else {
                    Toast.makeText(MyTravelNoteActivity.this, "评论不能为空", Toast.LENGTH_LONG)
                            .show();
                }
                editText.setText("");
            }
        });
        GetVolleyHttp.getInstance(MyTravelNoteActivity.this).getStringGETJsonData(UrlConfig.URL_TRAVEL_NOTE_ONE + id,
                listener, errorlistener,Long.decode("0"));
    }

    Response.Listener<String> listener1 = new Response.Listener<String>() {
        @Override
        public void onResponse(String json) {
            Log.e("json", json);
            TravelNotesListPostBean travelNotesListPostBean = JSON.parseObject(json, TravelNotesListPostBean.class);
            if (travelNotesListPostBean.getCode() == 0) {
                for (int i = 0; i < travelNotesListPostBean.getResults().size(); i++) {
                    commentLinearLayout.addView(createLin(MyTravelNoteActivity.this, travelNotesListPostBean.getResults().
                            get(i).getName(), travelNotesListPostBean.getResults().get(i).getContent()));
                }

            } else {
                Toast.makeText(MyTravelNoteActivity.this, "评论失败", Toast.LENGTH_LONG)
                        .show();
            }
        }
    };
    // 当网络请求返回状态不成功（也就不是200）
    Response.ErrorListener errorlistener1 = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError arg0) {
            Toast.makeText(MyTravelNoteActivity.this, "评论失败", Toast.LENGTH_LONG)
                    .show();
        }
    };
    // 当网络请求返回成功（200的状态）
    Response.Listener<String> listener = new Response.Listener<String>() {

        @Override
        public void onResponse(String jsonstring) {

            // 开始解析JSON
            // 反序列化，直接将JSON反序列化为Test这个Class对象
            final MyTravelNoteBean resultslist = JSON.parseObject(jsonstring, MyTravelNoteBean.class);
            resultsList = resultslist.getResults();

            textViewTitle.setText(resultsList.get(0).getTitle());
            textViewTime.setText(resultsList.get(0).getPubdate());
            textViewAuthor.setText("作者：" + resultsList.get(0).getAuthor());
            textViewContent.setText(resultsList.get(0).getContent());

            for (int i = 0; i < resultsList.get(0).getCommentJsonList().size(); i++) {
                commentLinearLayout.addView(createLin(MyTravelNoteActivity.this, resultsList.get(0).getCommentJsonList().get(i).getName(),
                        resultsList.get(0).getCommentJsonList().get(i).getContent()));
            }

            LinearLayout linearLayout = (LinearLayout) findViewById(R.id.my_travel_one_dot);
            if (resultsList.get(0).getFilesList().size() != 0 && !resultsList.get(0).getFilesList().isEmpty()) {
                relativeLayout.setVisibility(View.VISIBLE);
                for (int i = 0; i < resultsList.get(0).getFilesList().size(); i++) {
                    LinearLayout linearLayout1 = new LinearLayout(MyTravelNoteActivity.this);
                    ViewGroup.LayoutParams ltp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT);
                    LinearLayout.LayoutParams margin = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.WRAP_CONTENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT);
                    final ImageView itemImageView = new ImageView(MyTravelNoteActivity.this);
                    itemImageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        GetVolleyHttp.getInstance(MyTravelNoteActivity.this).setImageLoader(itemImageView,
                                R.drawable.error_image, R.drawable.error_image, UrlConfig.URL + resultsList.get(0).getFilesList().get(i).getPath());
                    linearLayout1.addView(itemImageView, ltp);
                    viewList.add(linearLayout1);
                    //设置小圆点
                    ImageView imageView = new ImageView(MyTravelNoteActivity.this);
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                    margin.setMargins(10, 0, 0, 0);
                    imageViewList.add(imageView);
                    //如果图片只有一张 则不显示
                    if (resultsList.get(0).getFilesList().size() > 1) {
                        if (i == 0) {
                            // 默认选中第一张图片
                            imageView.setImageResource(R.drawable.scenic_tour_round_after_click_click);
                        } else {
                            //其他图片都设置未选中状态
                            imageView.setImageResource(R.drawable.scenic_tour_round_after_click_unclick);
                        }
                    }
                    //将image添加到布局中
                    linearLayout.addView(imageView, margin);
                }
            }
            vp.setAdapter(new ViewPagerAdapter(viewList));

        }

    };

    // 当网络请求返回状态不成功（也就不是200）
    Response.ErrorListener errorlistener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError arg0) {
            Toast.makeText(MyTravelNoteActivity.this, "网络出了些小问题", Toast.LENGTH_LONG)
                    .show();

        }
    };

    /**
     * 生成含有两个TextView的LinearLayout
     *
     * @param context
     * @param person
     * @param content
     * @return
     */
    private static LinearLayout createLin(Context context, final String person, final String content) {
        LinearLayout linearLayout = new LinearLayout(context);
        LinearLayout.LayoutParams margin = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        TextView textViewPerson = new TextView(context);
        TextView textViewContent = new TextView(context);
        textViewPerson.setText(person + "：");
        textViewPerson.setTextColor(Color.BLUE);
        textViewContent.setTextColor(Color.BLACK);
        textViewContent.setText(content);
        linearLayout.addView(textViewPerson, margin);
        linearLayout.addView(textViewContent, margin);
        return linearLayout;
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int arg0) {
//遍历数组让当前选中图片下的小圆点设置颜色
        for (int i = 0; i < imageViewList.size(); i++) {
            imageViewList.get(i).setImageResource(R.drawable.scenic_tour_round_after_click_click);
            if (arg0 != i) {
                imageViewList.get(i)
                        .setImageResource(R.drawable.scenic_tour_round_after_click_unclick);
            }

        }
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }
}
